package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BusinessException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.po.SetmealPO;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    //事务绑定
    @Transactional
    //添加菜品信息
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        //DTO转PO
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        //补全数据
        dish.setStatus(1);
        //向菜品信息表中插入一条数据
        dishMapper.insert(dish);
        //获取insert语句生成的主键值
        Long dishId = dish.getId();
        //获取关联口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                try {
                    dishFlavor.setDishId(dishId);
                } catch (Exception e) {
                    throw new BusinessException(500, "菜品信息已经存在");
                }
            });
            //向口味中插入数据
            dishFlavorMapper.addflavor(flavors);
        }
    }

    //分页查询
    @Override
    public PageResult page(DishPageDTO dishPageDTO) {
        //开启分页
        PageHelper.startPage(dishPageDTO.getPage(), dishPageDTO.getPageSize());
        //查询
        List<DishVO> list = dishMapper.list(dishPageDTO);
        PageInfo<DishVO> pageInfo = new PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    //批量删除
    @Override
    @Transactional
    public void deleteBatch(Long[] ids) {
        //1.参数校验
        if(ids == null || ids.length < 1){
            return;
        }
        //2.业务校验
        //2.1 统计启售状态的菜品数量
        Integer num = dishMapper.countByIdsAndStatus(ids,StatusConstant.ENABLE);
        if(num > 0){
            throw new BusinessException(500,"有启售状态的菜品，不能删除");
        }
        //2.2 遍历菜品id,根据dishid查询套餐菜品，如果关联了套餐，就不能删除
        for (Long dishId : ids) {
            num = setmealDishMapper.countByDishId(dishId);
            if(num > 0){
                //查询菜品具体信息，给用户一个准备的提示
                Dish dish = dishMapper.getById(dishId);
                throw new BusinessException(500,"当前菜品【"+dish.getName()+"】关联了套餐，不能删除");
            }
            //3.完成业务
            //3.1 删除菜品
            dishMapper.deleteById(dishId);
            //3.2 删除菜品口味
            dishFlavorMapper.deleteByDishId(dishId);
        }
    }

    //回显
    @Override
    public DishVO getByIdWithFlavor(Long dishId) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(dishId);
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.listByDishId(dishId);
        //将查询到的数据封装到VO
        DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    //修改
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //拷贝菜品相关数据
        Dish dish = BeanUtil.copyProperties(dishDTO, Dish.class);
        //修改菜品表基本信息
        dishMapper.update(dish);
        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.addflavor(flavors);
        }
    }
    @Autowired
    SetmealMapper setmealMapper;

    /**
     * 菜品的起售停售
     * @param status
     * @param dishId
     */
    @Override
    @Transactional
    public void enableOrDisable(Integer status, Long dishId) {
        //停售 需要停止售卖对应的套餐
        Dish dish = Dish.builder()
                .id(dishId)
                .status(status)
                .build();
        //修改菜品的状态
        dishMapper.update(dish);
        //修改菜品关联的套餐状态
        if (status == 0) {

            SetmealPO setmealPO = SetmealPO.builder()
                    .dishId(dishId)
                    .status(status)
                    .build();
            setmealMapper.updateStatusByDishId(setmealPO);
        }
    }



    /**
     * 根据分类ID查询启售菜品列表
     * @param dishDTO
     * @return
     */
    @Override
    public List<Dish> listById(DishDTO dishDTO) {
        if (dishDTO.getCategoryId()==null){
            throw new BusinessException(500,"商品分类ID不能为空");
        }
        //条件查询
        return dishMapper.paramsList(dishDTO);
    }

    /**
     * 根据分类id查询启售的菜品列表（包含口味）
     * @param dishDTO
     * @return
     */
    @Override
    public List<DishVO> appList(DishDTO dishDTO) {
        //1. 根据分类id查询启售的菜品列表信息
        List<Dish> dishList = dishMapper.paramsList(dishDTO);
        //2.　遍历菜品列表根据菜品id查询口味
        //2.1 准备存放dishVO的集合
        ArrayList<DishVO> voList = new ArrayList<>();
        dishList.forEach(dish -> {
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dish.getId());
            //封dishVO对象
            DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
            dishVO.setFlavors(flavors);
            voList.add(dishVO);
        });
        //2.1 把口味设置给菜品
        return voList;
    }

    @Override
    public Dish getById(Long id) {

        return dishMapper.getById(id);
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @Override
    public List<Dish> listByIds(Long... ids) {

        return dishMapper.getByIds(ids);
    }
}